#include <iostream>
#include <stdlib.h>

#include <time.h>
#include "HenkoCppLib.h"

using namespace std;
using namespace HenkoCppLib;

float MeasureMilliseconds(void (*function)(void))
{
	clock_t start, finish;
	start = clock();

	function();

	finish = clock();
	return ((finish-start)/(float)CLOCKS_PER_SEC) * 1000;
}

int count = 500;

void func_malloc()
{
	int*** p = (int***)malloc(sizeof(int**) * count);
	for (int i = 0; i < count; i++)
	{
		p[i] = (int**)malloc(sizeof(int*) * count);
		for (int j = 0; j < count; j++)
		{
			p[i][j] = (int*)malloc(sizeof(int) * count);
		}
	}
	for (int i = 0; i < count; i++)
	{
		for (int j = 0; j < count; j++)
		{
			free(p[i][j]);
		}
		free(p[i]);
	}
	free(p);
}

void func_new()
{
	int*** p = new int**[count];
	for (int i = 0; i < count; i++)
	{
		p[i] = new int*[count];
		for (int j = 0; j < count; j++)
		{
			p[i][j] = new int[count];
		}
	}
	for (int i = 0; i < count; i++)
	{
		for (int j = 0; j < count; j++)
		{
			delete[] p[i][j];
		}
		delete[] p[i];
	}
	delete[] p;
}

void func_smart()
{
	IntPtr3D p = new(p) IntPtr2D[count];
	for (int i = 0; i < count; i++)
	{
		p[i] = new(p[i]) IntPtr[count];
		for (int j = 0; j < count; j++)
		{
			p[i][j] = new(p[i][j]) int[count];
		}
	}
}

int main()
{
	float bestratio = 0;
	cout << "MALLOC/NEW - VS - SMART   : RATIO" << endl;
	for (int i = 0; i < 10; i++)
	{
		float ms1 = MeasureMilliseconds(func_malloc);
		float ms2 = MeasureMilliseconds(func_new);
		float ms3 = MeasureMilliseconds(func_smart);
		float ratio = ms2 / ms3;
		cout << ms1 << "/" << ms2 << "    - VS - " << ms3 << "     : " << ratio << endl;
		if (ratio > bestratio) bestratio = ratio;
	}
	cout << "Best ratio: " << bestratio << endl;
}
